data = {
	'lastID' 		: 0,
	'noActivity'	: 0,
	'id_patient'	: $('#id_patient').val(),
	'id_nutritionist'	: $('#id_nutritionist').val(),
	'isQuestion'	: $('#isQuestion').val()
}
	
$(document).ready(function(){
	init();	
});

function init(){

	// We use the working variable to prevent
	// multiple form submissions:
	var working = false;


	// Quando envia um novo texto:
	$('#submitForm').submit(function(){

		var text = $('#chatText').val();

		if(text.length == 0){
			return false;
		}

		if(working) return false;
		working = true;

		// Assigning a temporary ID to the chat:
		var tempID = 't'+Math.round(Math.random()*1000000),
			params = {
				id			: tempID,
				id_patient	: data.id_patient,
				id_nutritionist	: data.id_nutritionist,
				isQuestion	: data.isQuestion,
				text		: text.replace(/</g,'&lt;').replace(/>/g,'&gt;')
			};

		// Using our addChatLine method to add the chat
		// to the screen immediately, without waiting for
		// the AJAX request to complete:
		//CONFUSO
		addChatLine($.extend({},params));

		// Using our tzPOST wrapper method to send the chat
		// via a POST AJAX request:
		dataPost = { 
			id_patient: data.id_patient,
			id_nutritionist: data.id_nutritionist,
			isQuestion: data.isQuestion,
			chatText: text.replace(/</g,'&lt;').replace(/>/g,'&gt;')
		};
		
		tzPOST('submitChat',dataPost,function(r){
			if(r.status == '1'){
				working = false;

				//Limpa a caixa de texto
				$('#chatText').val('');

				//Remove o temporario e insere o real
				$('div.chat-'+tempID).remove();
				params['id'] = r.insertID;

				//CONFUSO
				addChatLine($.extend({},params));
			}
			else{
				//chat.displayError(r.problem);
			}
		});

		return false;
	});

	
	// Self executing timeout functions
	(function getChatsTimeoutFunction(){
		getChats(getChatsTimeoutFunction);
	})();
}

// The render method generates the HTML markup 
// that is needed by the other methods:
function render(template,params){

	var arr = [];
	switch(template){
		case 'chatLine':
			if(params.isQuestion == 0){
				params.author = "Liana";
				params.gravatar = "/application/images/icons/foto-chat.jpg";
			}else{
				params.author = "Eu";
			}
			arr = [
				'<div class="chat chat-',params.id,' rounded"><span class="gravatar"><img src="',params.gravatar,
				'" width="23" height="23" onload="this.style.visibility=\'visible\'" />','</span><span class="author">',params.author,
				':</span><span class="text">',params.text,'</span><span class="time">',params.time,'</span></div>'];
		break;
	}

	// A single array join is faster than
	// multiple concatenations

	return arr.join('');

}
	
// The addChatLine method ads a chat entry to the page
function addChatLine(params){
	// All times are displayed in the user's timezone
	var d = new Date();
	if(params.time) {

		// PHP returns the time in UTC (GMT). We use it to feed the date
		// object and later output it in the user's timezone. JavaScript
		// internally converts it for us.

		d.setUTCHours(params.time.hours,params.time.minutes);
	}

	params.time = (d.getHours() < 10 ? '0' : '' ) + d.getHours()+':'+
					(d.getMinutes() < 10 ? '0':'') + d.getMinutes();

	var markup = render('chatLine',params),
		exists = $('#chatLineHolder .chat-'+params.id);

	if(exists.length){
		exists.remove();
	}

	//Remover a mesnagem de boas vindas
	//if(!chat.data.lastID){ $('.chat-0').remove();	}

	// If this isn't a temporary chat:
	if(params.id.toString().charAt(0) != 't'){
		var previous = $('#chatLineHolder .chat-'+(+params.id - 1));
		if(previous.length){
			previous.after(markup);
		}
		else $('#chatLineHolder').append(markup);
	}
	else $('#chatLineHolder').append(markup);
}
	
// This method requests the latest chats
// (since lastID), and adds them to the page.
function getChats(callback){
	dataPost = { 
			id_patient: data.id_patient,
			id_nutritionist: data.id_nutritionist,
			lastID: data.lastID
		};
		
	tzGET('getChats',dataPost,function(r){
		for(var i=0;i<r.chats.length;i++){
			addChatLine(r.chats[i]);
		}

		if(r.chats.length){
			data.noActivity = 0;
			data.lastID = r.chats[i-1].id;
		}
		else{
			// If no chats were received, increment
			// the noActivity counter.

			data.noActivity++;
		}

		if(!data.lastID){
			paramInit = {
				id			: 0,
				id_patient	: 0,
				id_nutritionist	: 0,
				isQuestion	: 0,
				text		: "Olá! Seja bem vindo ao chat. Aqui você poderá entrar em contato comigo a qualquer hora do dia que responderei o mais breve possível!"
			};
			msgBemVindo = render('chatLine',paramInit);
			$('#chatLineHolder').html(msgBemVindo);

		}

		// Setting a timeout for the next request,
		// depending on the chat activity:

		var nextRequest = 1000;

		// 2 seconds
		if(data.noActivity > 3){
			nextRequest = 2000;
		}

		if(data.noActivity > 10){
			nextRequest = 5000;
		}

		// 15 seconds
		if(data.noActivity > 20){
			nextRequest = 15000;
		}
		setTimeout(callback,nextRequest);
	});

}
	   
// This method displays an error message on the top of the page:
function displayError(msg){
	var elem = $('<div>',{
		id		: 'chatErrorMessage',
		html	: msg
	});

	elem.click(function(){
		$(this).fadeOut(function(){
			$(this).remove();
		});
	});

	setTimeout(function(){
		elem.click();
	},5000);

	elem.hide().appendTo('body').slideDown();
}

// Custom GET & POST wrappers:
function tzPOST(action,data,callback){
	$.post('/ajax/'+action,data,callback,'json');
}

function tzGET(action,data,callback){
	$.get('/ajax/'+action,data,callback,'json');
}
